package jenry.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import jenry.model.Mp3Info;
import android.os.Environment;

public class FileUtils {
	private String SDPATH;
	
	public String getSDPATH(){
		return SDPATH;
	}
	
	public FileUtils(){
		SDPATH = Environment.getExternalStorageDirectory()+"/";
	}
	
	public File createSDFile(String fileName) throws IOException{
		File file = new File (SDPATH+fileName);
		file.createNewFile();
		return file;
	}
	
	public File createSDDir (String dirName){
		File dir = new File(SDPATH + dirName);
		dir.mkdirs();
		return dir;
	}
	
	public boolean isFileExist(String fileName){
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	public File write2SDFormInput(String path,String fileName,InputStream input){
		File file = null;
		OutputStream output = null;
		
		try{
			createSDDir(path);
			file = createSDFile(path + fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4*1024];
			while((input.read(buffer)) != -1){
				output.write(buffer);
			}
			output.flush();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				output.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
	
	public List<Mp3Info> getMp3Files(String path){
		List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
		File file = new File(SDPATH+File.separator+path);
		File[] files = file.listFiles();
		for(int i= 0;i<files.length; i++){
			if(files[i].getName().endsWith("mp3")){
				Mp3Info mp3Info = new Mp3Info();
				mp3Info.setMp3Name(files[i].getName());
				mp3Info.setMp3Size(files[i].length()+"");
				mp3Infos.add(mp3Info);
			}
		}
		return mp3Infos;
	}
}
